//
//  ContactsDetailViewController.m
//  SIPphone
//
//  Created by wrt on 13-11-26.
//  Copyright (c) 2013年 wrtsoft. All rights reserved.
//

#import "ContactsDetailViewController.h"
#import "CallViewController.h"
#import "ContactsDateBase.h"
#import "PromptChatDateBase.h"
#import "PromptChatVCViewController.h"
#import "SIPInterface.h"
#import "HistoryDataBase.h"

@interface ContactsDetailViewController ()

@end

@implementation ContactsDetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

//初始化方法将数据传入
- (id)initWithUserName:(NSString *)userName andDisplayName:(NSString *)displayName andStatus:(NSString *)status andMarkName:(NSString *)markName andIP:(NSString *)ip andIsFriend:(NSString *)isFriend
{
    self = [super init];
    if (self)
    {
        tempUserName = [[NSString alloc] init];
        tempDisplayName = [[NSString alloc] init];
        tempMarkName = [[NSString alloc] init];
        tempIP = [[NSString alloc] init];
        tempStatus = [[NSString alloc] init];
        tempIsFriend = [[NSString alloc] init];
        tempUserName = userName;
        tempDisplayName = displayName;
        tempStatus = status;
        tempIP = ip;
        tempIsFriend = isFriend;
        tempMarkName = markName;
    }
    return self;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    SIPInterface *interface = [SIPInterface shareSIPInterface];
    interface.delegate = self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = tempMarkName;
    // Do any additional setup after loading the view from its nib.
    self.userNameLabel.text = tempUserName;
    self.displayNameLabel.text = tempDisplayName;
    self.nowStatusLabel.text = tempStatus;
    self.markNameTextField.text = tempMarkName;
    self.ipLabel.text = tempIP;
    self.isFriendLabel.text = tempIsFriend;
    
//    if (![tempIsFriend isEqualToString:@"好友"])
//    {
//        [self.sendMessageButton setHidden:YES];
//        [self.nowStatusLabel setHidden:YES];
//    }
    SIPInterface *interface = [SIPInterface shareSIPInterface];
    interface.delegate = self;
    
    //将删除联系人的按钮 放置在导航栏的右上角
    UIBarButtonItem *deleteContactsButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"delete_64.png"] style:UIBarButtonItemStyleBordered target:self action:@selector(deleteContactsForBD)];
    self.navigationItem.rightBarButtonItem = deleteContactsButton;
}

- (IBAction)callButtonPressed:(id)sender
{
    //先判断是否是登陆状态，如果不是登陆状态则提示请登陆
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    BOOL registerStatus = [defaults boolForKey:@"REGISTERSTATUS"];
    if (registerStatus && tempUserName.length > 1)
    {
        SIPInterface *interface = [SIPInterface shareSIPInterface];
        [interface start_Call:tempUserName];
        
        HistoryDataBase *historyDB = [HistoryDataBase shareHistoryDataBase];
        [historyDB writeIntoDatabaseWithNumber:tempUserName andDisplayName:tempDisplayName]; //将拨出的号码记录下来存到数据库中
    }
    else if(!registerStatus)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"notice", @"通知 notice") message:NSLocalizedString(@"please log in", @"请先登陆 Please log in") delegate:nil cancelButtonTitle:NSLocalizedString(@"OK", @"好的 OK") otherButtonTitles: nil];
        [alert show];
    }
}

- (IBAction)markNameTextFieldDidEnd:(id)sender
{
    [self.markNameTextField resignFirstResponder];
}

- (IBAction)backgroundTouch:(id)sender
{
    [self.markNameTextField resignFirstResponder];
}

- (IBAction)editMarkNameButtonPressed:(id)sender
{
    if ([self.markNameTextField.text isEqualToString:tempMarkName])
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"notice", @"通知 notice") message:NSLocalizedString(@"no change", @"没有改变 No change") delegate:self cancelButtonTitle:NSLocalizedString(@"OK", @"好的 OK") otherButtonTitles: nil];
        [alert show];
    }
    else
    {
        ContactsDateBase *contactsDB = [ContactsDateBase shareContactsDataBase];
        for (int i = 0 ; i < contactsDB.userNameArray.count ; i++)
        {
            if([self.markNameTextField.text isEqualToString:contactsDB.markNameArray[i]])
            {
                //数据库进行更新
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"notice", @"通知 notice") message:NSLocalizedString(@"remarks the same name already exists, in order to avoid data corruption. Please modify Remarks name to add, thank you", @"已存在相同的备注名，为了避免数据出错。请修改备注名再添加，谢谢合作 Remarks the same name already exists, in order to avoid data corruption. Please modify Remarks name to add, thank you") delegate:nil cancelButtonTitle:NSLocalizedString(@"OK", @"好的 OK") otherButtonTitles: nil];
                [alert show];
                return;
            }
        }
        
        [contactsDB updateDBForMarkNameWithUserName:tempUserName andIp:tempIP andNewMarkName:self.markNameTextField.text];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"notice", @"通知 notice") message:NSLocalizedString(@"successfully modified", @"修改成功 Successfully modified") delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
        [alert show];
        
        [self performSelector:@selector(returnViewController) withObject:self afterDelay:0.8];
        
        
        [alert dismissWithClickedButtonIndex:0 animated:YES];
    }
}

- (IBAction)sendMessageButtonPressed:(id)sender
{
    
    
    PromptChatVCViewController *promptChatVC = [[PromptChatVCViewController alloc] initWithUserName:tempUserName andIpport:tempIP andMarkName:tempMarkName];
    promptChatVC.titleStr = [[NSString alloc] init];
    promptChatVC.titleStr = tempMarkName;
    promptChatVC.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    SIPInterface *interface = [SIPInterface shareSIPInterface];
    unsigned long windowId = [interface getChatRoomByUserName:tempUserName andIPport:tempIP andPort:@"24741"];
    //原本为5060
    if (windowId == 0)
    {
        [interface creatChatRoomWithUserName:tempUserName];
    }
    else
    {
        [PromptChatDateBase sharePromptChatDB].windowID = windowId;
    }
    [self presentModalViewController:promptChatVC animated:YES];
    
}

#pragma mark -
#pragma mark SIPlistenMethod

- (void)registerSuccessful //注册成功时的操作
{
    dispatch_async(dispatch_get_main_queue(),^{
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setBool:YES forKey:@"REGISTERSTATUS"];
        [defaults synchronize];
    });
}

- (void)registerFailed  //注册失败时的操作
{
    dispatch_async(dispatch_get_main_queue(),^{
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setBool:NO forKey:@"REGISTERSTATUS"];
        [defaults synchronize];
    });
}

- (void)outgoingCallBegin  //主动呼叫开始
{
    dispatch_async(dispatch_get_main_queue(),^{
        CallViewController *callVC = [[CallViewController alloc] initWithNumber:tempUserName];
        callVC.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
        [self presentModalViewController:callVC animated:YES];
    });
}

- (void)callEnding
{
    
}

- (void)openWindow
{
    
}

- (void)deleteContactsForBD
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"notice", @"通知 notice") message:NSLocalizedString(@"are you sure you want to delete this contact?", @"你确定要删除该联系人吗？ Are you sure you want to delete this contact?") delegate:self cancelButtonTitle:NSLocalizedString(@"sure", @"确定 Sure") otherButtonTitles:NSLocalizedString(@"cancel", @"取消 cancel"), nil];
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1)
    {
        
    }
    if (buttonIndex == 0)
    {
        ContactsDateBase *contactsdb = [ContactsDateBase shareContactsDataBase];
        [contactsdb deleteContactsBDWithUserName:tempUserName andIpPort:tempIP];
        
//        SIPInterface *interface = [SIPInterface shareSIPInterface];
//        if ([tempUserName isEqualToString:tempDisplayName])
//        {
//            [interface deleteFriendWithUserName:tempUserName andDisPlayName:@"" andIp:tempIP];
//        }
//        else
//        {
//            [interface deleteFriendWithUserName:tempUserName andDisPlayName:tempDisplayName andIp:tempIP];
//        }
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:NSLocalizedString(@"deleted successfully", @"删除成功 Deleted successfully") delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
        [alert show];
        [self performSelector:@selector(returnViewController) withObject:self afterDelay:0.5];
        
        [alert dismissWithClickedButtonIndex:0 animated:YES];
    }
}

- (void)returnViewController
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
